<script lang="ts" setup>
  import { ref } from 'vue';
  import { useAppStore } from '@/store';
  import Edit from './edit/index.vue';
  import Add from './add/index.vue';
  import Comment from './comment/index.vue';
  import MoveFile from './movefile/index.vue';
  import { deleteDoc, getdocList, lockDoc, unlockDoc } from '@/api/dashboard';
  import { Message, Modal, TableInstance } from '@arco-design/web-vue';
  import usePageStore from '@/store/modules/page';
  import { delectDept } from '@/api/syssetting';
  defineOptions({
    name: 'fileCenter',
  });
  const proTableRef = ref<TableInstance | null>(null);
  const appStore = useAppStore();
  const visible = ref(false);
  const visible1 = ref(false);
  const visible2 = ref(false);
  const visible3 = ref(false);
  const currentParams = ref();
  const currentImage = ref();
  const showImaeg = ref(false);
  const showDocx = ref(false);
  const getPreviewUrl = (url: string) => {
    return `https://view.officeapps.live.com/op/embed.aspx?src=${url}`;
  };

  const handleOpenFile = (record: any) => {
    const ext = record.doc_file_extension;
    const url = import.meta.env.VITE_FILE_PATH + record.doc_file;
    // 图片类型
    const imageTypes = ['png', 'jpg', 'jpeg', 'svg', 'gif', 'webp'];
    if (imageTypes.includes(ext)) {
      currentImage.value = url;
      showImaeg.value = true;
      return 'img';
    }
    // PDF
    const pdfType = ['pdf'];
    if (pdfType.includes(ext)) {
      console.log('pdfType');
      return 'pdf';
    }
    // 视频类型
    const videoTypes = ['mp4', 'avi', 'mov'];
    if (videoTypes.includes(ext)) {
      console.log('这是视频文件，执行视频相关操作');
      return 'video';
    }

    // 音频类型
    if (ext === 'mp3') {
      console.log('这是音频文件，执行音频相关操作');
      return 'audio';
    }

    // 文档类型
    const documentTypes = ['docx', 'doc', 'txt'];
    if (documentTypes.includes(ext)) {
      // 打开一个新的文件
      console.log(currentImage.value);
      window.open(getPreviewUrl(currentImage.value), '_blank');
      return 'document';
    }

    // 表格类型
    const spreadsheetTypes = ['xls', 'xlsx'];
    if (spreadsheetTypes.includes(ext)) {
      console.log('这是表格文件，执行表格相关操作');
      return 'spreadsheet';
    }

    // 演示文稿类型
    const presentationTypes = ['ppt', 'pptx'];
    if (presentationTypes.includes(ext)) {
      console.log('这是演示文稿文件，执行演示文稿相关操作');
      return 'presentation';
    }

    // 压缩文件类型
    const archiveTypes = ['zip', 'rar', '7z'];
    if (archiveTypes.includes(ext)) {
      console.log('这是压缩文件，执行压缩文件相关操作');
      return 'archive';
    }
    // 打不开就直接下载
    Message.error('该文件不支持打开！');
    return 'unknown';
  };
  const formType = ref([
    {
      name: 'doc_name',
      label: '文档名',
      type: 'a-input',
      fieldProps: {
        span: 8,
        width: 50,
      },
    },
    {
      name: 'doc_number',
      label: '文档编号',
      type: 'a-input',
      fieldProps: {
        span: 8,
      },
    },
  ]);
  const tableType = [
    { dataIndex: 'doc_id', title: '编号', align: 'center', width: 60 },
    {
      title: '文档名',
      dataIndex: 'doc_name',
      slotName: 'iconTitle',
      iconName: 'doc_file_extension',
      linkName: 'doc_file',
      onClick: handleOpenFile,
    },
    {
      title: '文档类型',
      dataIndex: 'doc_type_name',
      align: 'center',
      width: 105,
    },
    {
      title: '文件类型',
      dataIndex: 'doc_file_extension',
      align: 'center',
      width: 90,
    },
    {
      title: '文件大小',
      dataIndex: 'doc_file_size',
      align: 'center',
      width: 90,
    },
    {
      title: '文件摘要',
      dataIndex: 'doc_desc',
      align: 'center',
      width: 130,
    },
    {
      title: '文档锁定',
      dataIndex: 'doc_lock',
      align: 'center',
      slotName: 'status',
      width: 90,
      options: [
        {
          status: 'success',
          value: 1,
          label: '正常',
        },
        {
          status: 'danger',
          value: 2,
          label: '已锁定',
        },
      ],
    },
    {
      title: '发布人',
      dataIndex: 'doc_user_name',
      width: 90,
    },
    {
      title: '发布时间',
      dataIndex: 'create_time',
      width: 180,
    },
    {
      title: '操作',
      width: 130,
      fixed: 'right',
      slotName: 'operations',
      menus: [
        {
          name: '编辑',
          onClick: (record: any) => {
            visible1.value = true;
            currentParams.value = {
              id: record.doc_id,
            };
          },
        },
        {
          name: '删除',
          onClick: (record: any) => {
            deleteDoc({
              doc_ids: [record.doc_id],
            }).then((res) => {
              proTableRef.value?.setRefresh();
              Message.success('删除成功！');
            });
          },
        },
      ],
    },
  ];

  const pageStore = usePageStore();

  async function request(params: any) {
    const res = await getdocList({
      ...params,
      type: pageStore.currentDirType,
      doc_dir_id: pageStore.dirId,
    });
    return {
      data: res.data,
    };
  }

  watch(
    () => pageStore.dirId,
    () => {
      proTableRef.value?.setRefresh();
    }
  ),
    {
      immediate: true,
      deep: true,
    };

  // 计算属性过滤重复元素
  const uniqueMethods = computed(() => {
    const uniqueSet = new Set();
    return appStore.fileMethods[0].filter((item: any) => {
      const key = JSON.stringify(item);
      if (!uniqueSet.has(key)) {
        uniqueSet.add(key);
        return true;
      }
      return false;
    });
  });

  function handleMethods(item: any) {
    switch (item.label) {
      case '新增':
        visible.value = true;
        break;
      case '删除':
        if (proTableRef.value?.selectedKeys.length === 0) {
          Message.error('请先选择后再删除！');
        } else {
          Modal.confirm({
            title: '系统提示',
            content: '确定要删除选中的文档吗？',
            okText: '确定',
            cancelText: '取消',
            onOk: () => {
              return new Promise((resolve, reject) => {
                deleteDoc({
                  doc_ids: proTableRef.value?.selectedKeys,
                }).then((res) => {
                  if (res?.code == 200) {
                    proTableRef.value.setRefresh();
                    Message.success(res?.msg);
                    resolve(true);
                  } else {
                    reject();
                  }
                });
              });
            },
          });
        }
        break;
      case '下载':
        if (proTableRef.value?.selectItems.length === 0) {
          Message.error('请先选择需要下载的文档！');
          return;
        }
        const selectedFiles = proTableRef.value?.selectItems;
        // 检测当前环境是否为HTTPS，若不是则提前提示
        if (window.location.protocol !== 'https:') {
          Modal.confirm({
            title: '安全提示',
            content:
              '当前文件通过HTTP连接提供，可能存在安全风险。是否继续下载？',
            okText: '继续下载',
            cancelText: '取消',
            onOk: () => {
              downloadMultipleFiles(selectedFiles);
            },
          });
        } else {
          // HTTPS环境直接下载
          Modal.confirm({
            title: '下载确认',
            content: `确定要下载选中的 ${selectedFiles.length} 个文档吗？`,
            okText: '确定',
            cancelText: '取消',
            onOk: () => {
              downloadMultipleFiles(selectedFiles);
            },
          });
        }
        break;
      case '评论':
        if (proTableRef.value?.selectedKeys.length === 0) {
          Message.warning('请先选择评论文档');
        } else if (proTableRef.value?.selectedKeys.length > 1) {
          Message.warning('只能选择一个评论文档');
        } else {
          visible2.value = true;
          currentParams.value = {
            id: proTableRef.value?.selectedKeys[0],
          };
        }
        break;
      case '移动':
        if (proTableRef.value?.selectedKeys.length === 0) {
          Message.warning('请先选择需要移动的文档');
        } else {
          visible3.value = true;
          currentParams.value = {
            id: proTableRef.value?.selectedKeys,
          };
        }
        break;
      case '锁定':
        if (proTableRef.value?.selectedKeys.length === 0) {
          Message.error('请先选择后再锁定！');
        } else {
          Modal.confirm({
            title: '系统提示',
            content: '确定要锁定选中的文档吗？',
            okText: '确定',
            cancelText: '取消',
            onOk: () => {
              return new Promise((resolve, reject) => {
                lockDoc({
                  doc_ids: proTableRef.value?.selectedKeys,
                }).then((res) => {
                  if (res?.code == 200) {
                    proTableRef.value.setRefresh();
                    Message.success(res?.msg);
                    resolve(true);
                  } else {
                    reject();
                  }
                });
              });
            },
          });
        }
        break;
      case '解锁':
        if (proTableRef.value?.selectedKeys.length === 0) {
          Message.error('请先选择后再解锁！');
        } else {
          Modal.confirm({
            title: '系统提示',
            content: '确定要解锁选中的文档吗？',
            okText: '确定',
            cancelText: '取消',
            onOk: () => {
              return new Promise((resolve, reject) => {
                unlockDoc({
                  doc_ids: proTableRef.value?.selectedKeys,
                }).then((res) => {
                  if (res?.code == 200) {
                    proTableRef.value.setRefresh();
                    Message.success(res?.msg);
                    resolve(true);
                  } else {
                    reject();
                  }
                });
              });
            },
          });
        }
        break;
    }
  }
  // 批量下载文件
  // 修改下载相关函数（替换原有的downloadFile和downloadMultipleFiles）
  const downloadFile = (filePath: string, fileName: string) => {
    return new Promise((resolve) => {
      const fullUrl = import.meta.env.VITE_API_BASE_URL + filePath;
      const link = document.createElement('a');
      // 处理URL编码（避免特殊字符导致的路径错误）
      link.href = encodeURI(fullUrl);
      link.download = fileName || filePath.split('/').pop() || 'download file';
      // 添加随机ID避免浏览器缓存或重复标签冲突
      link.id = `download-link-${Date.now()}-${Math.random()}`;
      document.body.appendChild(link);

      // 监听下载完成（通过load事件确认）
      link.addEventListener('load', resolve);
      link.addEventListener('error', resolve); // 错误也继续执行下一个
      link.click();

      // 延迟移除标签，确保下载触发完成
      setTimeout(() => {
        document.body.removeChild(link);
        resolve(true);
      }, 500);
    });
  };

  const downloadMultipleFiles = async (files: any[]) => {
    // 逐个下载，前一个完成后再执行下一个（避免浏览器限制）
    for (const file of files) {
      try {
        // 使用文件的原始名称作为下载文件名（更准确）
        await downloadFile(file.doc_file, file.doc_name);
        // 每个文件下载间隔增加随机延迟，降低浏览器拦截概率
        const delay = 500 + Math.random() * 500; // 500-1000ms随机延迟
        await new Promise((resolve) => setTimeout(resolve, delay));
      } catch (error) {
        console.error(`下载失败: ${file.doc_name}`, error);
        Message.warning(`文件 ${file.doc_name} 下载失败`);
      }
    }
    Message.success(`已完成 ${files.length} 个文件的下载尝试`);
  };
  //  设置标题
  const setTitle = () => {
    let title = '';
    switch (pageStore.currentDirType) {
      case 1:
        title = '公共文档';
        break;
      case 2:
        title = '个人文档';
        break;
      case 3:
        title = '归档文档';
        break;
    }
    return title;
  };
</script>

<template>
  <div class="container">
    <div class="panel">
      <pro-table
        ref="proTableRef"
        :title="setTitle()"
        :formType="formType"
        :request="request"
        :tableType="tableType"
        row-key="doc_id"
        show-rows
      >
        <template #btns>
          <div class="options" style="display: flex; align-items: center">
            <div
              class="options-item"
              v-for="(item, index) in uniqueMethods"
              :key="item.key || index"
              @click="handleMethods(item)"
            >
              <svg-icon
                :name="item.icon"
                style="height: 1.3em; width: 1.3em"
              ></svg-icon>
              <span>{{ item.label }}</span>
            </div>
          </div>
        </template>
        <template #options>
          <Add
            v-if="visible"
            v-model:visible="visible"
            @refresh="
              () => {
                $refs.proTableRef.setRefresh();
              }
            "
          />

          <Edit
            v-if="visible1"
            v-model:visible="visible1"
            :params="currentParams"
            @refresh="
              () => {
                $refs.proTableRef.setRefresh();
              }
            "
          />
          <Comment
            v-if="visible2"
            v-model:visible="visible2"
            :params="currentParams"
          />
          <MoveFile
            v-if="visible3"
            v-model:visible="visible3"
            :params="currentParams"
            @refresh="
              () => {
                $refs.proTableRef.setRefresh();
              }
            "
          />
        </template>
      </pro-table>
    </div>
    <a-image-preview :src="currentImage" v-model:visible="showImaeg" />
  </div>
</template>

<style lang="less" scoped>
  .container {
    padding-bottom: 0;
    background-color: var(--color-fill-2);

    .panel {
      background: #fff;
      box-sizing: border-box;
      border-radius: 3px;
      margin-left: -20px;

      .options {
        width: 100%;
        display: flex;
        flex-direction: row;
        align-items: center;
        flex-wrap: wrap;
        margin-bottom: -10px;
        &-item {
          display: flex;
          align-items: center;
          flex-direction: row;
          margin-right: 5px;
          padding: 8px 10px;
          box-sizing: border-box;
          border-radius: 3px;
          margin-bottom: 10px;
          &:hover {
            background: #f2f3f5;
          }
          span {
            margin-left: 3px;
            font-size: 13px;
            cursor: default !important;
          }
        }
      }
    }
  }
</style>
